package com.cabal.socket.controller;

import com.cabal.common.util.CabalGatewayMD5Util;
import com.cabal.common.util.HttpClientUtil;
import com.cabal.exchange.service.ItemExchangeService;
import com.cabal.mall.service.CabalMallService;
import com.cabal.module.security.SecurityAdminNoCheck;
import com.cabal.socket.KilledWebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

@Api(value = "服务端发送消息测试", tags = "服务端发送消息测试")
@RequestMapping("cabal/socket")
@RestController
@Slf4j
public class TestSocketServerController {

    @Value("${md5.secret_key}")
    private String secretKey;

    @Resource
    private CabalMallService cabalMallService;

    @Resource
    private ItemExchangeService itemExchangeService;

    @ApiOperation(value = "发送消息测试")
    @GetMapping("testSendMessage")
    @SecurityAdminNoCheck
    public String testSendMessage(@RequestParam("message") String message, HttpServletRequest request) {
        String ip = HttpClientUtil.getClientIp(request);
        log.info("客户端请求IP地址>>>>{}", ip);
        if(!"127.0.0.1".equals(ip)) {
            return "禁止访问";
        }
        String base64Message = Base64.getEncoder().encodeToString(message.getBytes());
        String encryptMessage = CabalGatewayMD5Util.md5(base64Message, secretKey, false);
        String sendMessage = "GG|".concat(encryptMessage).concat("|").concat(base64Message);
        KilledWebSocketServer.sendMessageAll(sendMessage);
        return "SUCCESS";
    }

    @ApiOperation(value = "发送商城币")
    @GetMapping("sendMallCoin")
    @SecurityAdminNoCheck
    public String sendMallCoin(@RequestParam(name="account", required=false) String account, @RequestParam(name="mallCoin", required=false) String mallCoin, HttpServletRequest request) {
        String ip = HttpClientUtil.getClientIp(request);
        log.info("发送商城币客户端请求IP地址>>>>{}", ip);
        if(!"127.0.0.1".equals(ip)) {
            return "禁止访问";
        }

        cabalMallService.sendMallCoin(account, mallCoin);
        return "SUCCESS";
    }

    @ApiOperation(value = "发送0点物品")
    @GetMapping("itemSendEveryDay")
    @SecurityAdminNoCheck
    public String itemSendEveryDay(HttpServletRequest request) {
        String ip = HttpClientUtil.getClientIp(request);
        log.info("发送0点物品客户端请求IP地址>>>>{}", ip);
        if(!"127.0.0.1".equals(ip)) {
            return "禁止访问";
        }

        itemExchangeService.itemSendEveryDay();
        return "SUCCESS";
    }


}
